<template>
  <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click="handleBackdropClick">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
      <!-- 標題 -->
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-medium text-gray-900">
          {{ $t('share.title') }}
        </h3>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 分享预览卡片 -->
      <div class="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
        <div class="flex items-start space-x-4">
          <img
            v-if="post.pet?.photo_url"
            :src="getFullImageUrl(post.pet.photo_url)"
            :alt="post.pet.name"
            class="w-20 h-20 object-cover rounded-lg flex-shrink-0"
          />
          <div
            v-else
            class="w-20 h-20 bg-gray-200 rounded-lg flex items-center justify-center flex-shrink-0"
          >
            <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </div>
          <div class="flex-1 min-w-0">
            <h4 class="text-lg font-semibold text-gray-900 truncate">
              {{ $t('share.findingPet', { name: post.pet?.name }) }}
            </h4>
            <p class="text-sm text-gray-600 mt-1">
              {{ getPetSpeciesLabel(post.pet?.species) }} · {{ getPetColorLabel(post.pet?.color) }} ·
              {{ getPetGenderLabel(post.pet?.gender) }}
            </p>
            <p class="text-sm text-gray-500 mt-1">
              {{ $t('share.lostLocation', { location: post.last_seen_location }) }}
            </p>
            <p class="text-sm text-gray-500">
              {{ $t('share.lostTime', { time: formatDate(post.last_seen_time) }) }}
            </p>
          </div>
        </div>
      </div>

      <!-- 分享文本 -->
      <div class="mb-6">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          {{ $t('share.shareText') }}
        </label>
        <textarea
          v-model="shareText"
          rows="4"
          class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500"
        ></textarea>
      </div>

      <!-- 分享平台 -->
      <div class="mb-6">
        <h4 class="text-sm font-medium text-gray-700 mb-3">{{ $t('share.selectPlatform') }}</h4>
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <button
            v-for="platform in SHARE_PLATFORMS"
            :key="platform.name"
            @click="shareToplatform(platform)"
            class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:border-gray-300 hover:bg-gray-50 transition-colors"
          >
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center text-white mb-2"
              :style="{ backgroundColor: platform.color }"
            >
              <component :is="getPlatformIcon(platform.icon)" class="w-5 h-5" />
            </div>
            <span class="text-xs font-medium text-gray-900">{{ platform.name }}</span>
          </button>
        </div>
      </div>

      <!-- 複製鏈接 -->
      <div class="mb-6">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          {{ $t('share.copyLink') }}
        </label>
        <div class="flex">
          <input
            :value="shareUrl"
            readonly
            class="flex-1 px-3 py-2 border border-gray-300 rounded-l-md bg-gray-50 text-sm"
          />
          <button
            @click="copyLink"
            class="px-4 py-2 bg-primary-600 text-white rounded-r-md hover:bg-primary-700 text-sm font-medium"
          >
            {{ copied ? $t('share.copied') : $t('share.copy') }}
          </button>
        </div>
      </div>

      <!-- 原生分享 -->
      <div v-if="canUseNativeShare" class="mb-6">
        <button
          @click="nativeShare"
          class="w-full bg-gray-900 text-white px-4 py-3 rounded-lg font-medium hover:bg-gray-800"
        >
          {{ $t('share.nativeShare') }}
        </button>
      </div>

      <!-- 關閉按鈕 -->
      <div class="flex justify-end">
        <button
          @click="$emit('close')"
          class="btn-secondary"
        >
          {{ $t('share.close') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { copyToClipboard, formatDate, getFullImageUrl } from '@/utils/helpers'
import { usePetSpeciesOptions, usePetColorOptions, usePetGenderOptions } from '@/utils/i18n-options'
import type { Post } from '@/types'
import { SHARE_PLATFORMS } from '@/constants'

interface Props {
  post: Post
}

interface Emits {
  (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const { t } = useI18n()
const petSpeciesOptions = usePetSpeciesOptions()
const petColorOptions = usePetColorOptions()
const petGenderOptions = usePetGenderOptions()

// 狀態
const copied = ref(false)

// 計算屬性
const shareUrl = computed(() => {
  return window.location.origin + `/posts/${props.post.id}`
})

const shareText = ref('')

const canUseNativeShare = computed(() => {
  return 'share' in navigator
})

// 獲取寵物標籤的方法
const getPetSpeciesLabel = (species?: string) => {
  if (!species) return t('common.unknown')
  const option = petSpeciesOptions.find((opt: any) => opt.value === species)
  return option?.label || species
}

const getPetColorLabel = (color?: string) => {
  if (!color) return t('common.unknown')
  const option = petColorOptions.find((opt: any) => opt.value === color)
  return option?.label || color
}

const getPetGenderLabel = (gender?: string) => {
  if (!gender) return t('common.unknown')
  const option = petGenderOptions.find((opt: any) => opt.value === gender)
  return option?.label || gender
}

// 方法
const handleBackdropClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    emit('close')
  }
}

const generateShareText = () => {
  const pet = props.post.pet
  return `${t('share.urgentSearch')}

${t('share.petName', { name: pet?.name })}
${t('share.breed', { breed: getPetSpeciesLabel(pet?.species) })}
${t('share.color', { color: getPetColorLabel(pet?.color) })}
${t('share.gender', { gender: getPetGenderLabel(pet?.gender) })}
${t('share.lostLocation', { location: props.post.last_seen_location })}
${t('share.lostTime', { time: formatDate(props.post.last_seen_time) })}

${t('share.shareMessage')}

${t('share.detailLink', { url: shareUrl.value })}`
}

const shareToplatform = (platform: typeof SHARE_PLATFORMS[0]) => {
  const url = platform.getUrl(shareText.value, shareUrl.value)
  window.open(url, '_blank', 'width=600,height=400')
}

const copyLink = async () => {
  const success = await copyToClipboard(shareUrl.value)
  if (success) {
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  }
}

const nativeShare = async () => {
  if (!canUseNativeShare.value) return

  try {
    await navigator.share({
      title: t('share.shareTitle', { name: props.post.pet?.name }),
      text: shareText.value,
      url: shareUrl.value,
    })
  } catch (error) {
    console.log(t('share.shareCancelled'), error)
  }
}

const getPlatformIcon = (iconName: string) => {
  // 这里返回简单的SVG图标组件
  const icons: Record<string, any> = {
    whatsapp: () => 'W',
    facebook: () => 'f',
    twitter: () => 'T',
    telegram: () => 'T',
  }
  return icons[iconName] || (() => '?')
}

onMounted(() => {
  shareText.value = generateShareText()
})
</script>
